/*
 * Copyright (C) 2015 Drakeet <drakeet.me@gmail.com>
 *
 * This file is part of Meizhi
 *
 * Meizhi is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Meizhi is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Meizhi.  If not, see <http://www.gnu.org/licenses/>.
 */

package me.drakeet.meizhi;

import android.app.Application;
import android.content.Context;
import com.litesuits.orm.LiteOrm;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

import me.drakeet.meizhi.util.Toasts;

/**
 * Created by drakeet on 6/21/15.
 */
public class App extends Application {

    private static final String DB_NAME = "gank.db";
    public static Context sContext;
    public static LiteOrm sDb;


    @Override public void onCreate() {
        super.onCreate();
        sContext = this;
        Toasts.register(this);
        sDb = LiteOrm.newSingleInstance(this, DB_NAME);
        if (BuildConfig.DEBUG) {
            copyDBToSDcrad();
            sDb.setDebugged(true);
        }
    }
    @Override public void onTerminate() {
        super.onTerminate();
    }

    public void copyDBToSDcrad()
    {
        String DATABASE_NAME = DB_NAME;
        File oldFile = getApplicationContext().getDatabasePath(DATABASE_NAME);
//        String oldPath = "/data/data/com.landicorp.component.db/databases/" + DATABASE_NAME;
        String newPath = "/sdcard/tmp/" + DATABASE_NAME;

        copyFile(oldFile, newPath);
    }

    /**
     * 复制单个文件
     *
     * @param newPath
     *            String 复制后路径
     * @return boolean
     */
    public static void copyFile(File oldfile, String newPath)
    {
        try
        {
            int bytesum = 0;
            int byteread = 0;
            File newfile = new File(newPath);
            if (!newfile.exists())
            {
                newfile.createNewFile();
            }
            if (oldfile.exists())
            { // 文件存在时
                InputStream inStream = new FileInputStream(oldfile); // 读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                while ((byteread = inStream.read(buffer)) != -1)
                {
                    bytesum += byteread; // 字节数 文件大小
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        }
        catch (Exception e)
        {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();

        }

    }

}
